import random

from flask_restful import Resource, reqparse
import requests
import json
from huiyan.extions import cache, db
from huiyan.models.Project import Project

# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, default='')
parser.add_argument('id', type=int, default=0)


# 新建项目
class ProjectController(Resource):
    def post(self):
        args = parser.parse_args()
        name: str = args.get('name')

        try:
            p = Project(name=name)
            db.session.add(p)
            db.session.flush()
            db.session.commit()
            return {
                'status': 200,
                'msg': '添加成功',
                "p": {
                    "name": name,
                    "id": p.id
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'status': 400,
                'msg': '添加失败',
            }

    def get(self):
        p_lists = Project.query.filter_by(is_delete=False).all()
        data = [{
            "id": p.id,
            "name": p.name
        } for p in p_lists]

        return {
            'status': 200,
            "data": data
        }

    def put(self):
        args = parser.parse_args()
        id: int = args.get('id')
        name: str = args.get('name')

        p: Project = Project.query.get(id)
        if p:
            p.name = name

            db.session.commit()
            return {
                'status': 200,
                'msg': '修改成功'
            }
        return {
            'status': 400,
            'msg': '修改失败'
        }

    def delete(self):
        args = parser.parse_args()
        id: int = args.get('id')

        p: Project = Project.query.get(id)
        if p:
            p.is_delete = True
            db.session.commit()
            return {
                'status': 200,
                'msg': '删除成功'
            }
        return {
            'status': 400,
            'msg': '删除失败'
        }